//
//  UILabel+EL.m
//  jobClient
//
//  Created by 一览ios on 2017/4/24.
//  Copyright © 2017年 YL1001. All rights reserved.
//

#import "UILabel+EL.h"

@implementation UILabel (EL)

/**
 改变部分文字字体大小

 @param subString 需要改变的文字
 @param fontSize 改变后的字体大小
 */
- (void)subString:(NSString *)subString fontSize:(CGFloat)fontSize {
    NSString *fontName = self.font.fontName;
    [self subString:subString font:[UIFont fontWithName:fontName size:fontSize]];
}

/**
 改变部分文字字体

 @param subString 需要改变的文字
 @param font 改变后的字体
 */
- (void)subString:(NSString *)subString font:(UIFont *)font {
    [self subString:subString font:font color:nil];
}

/**
 改变部分文字颜色

 @param subString 需要改变的文字
 @param color 改变后的颜色
 */
- (void)subString:(NSString *)subString color:(UIColor *)color {
    [self subString:subString font:nil color:color];
}

/**
 改变部分文字字体和颜色

 @param subString 需要改变的文字
 @param font 改变后的字体
 @param color 改变后的颜色
 */
- (void)subString:(NSString *)subString font:(UIFont *)font color:(UIColor *)color {
    if (StringIsEmpty(subString)) return;
    if (!self.attributedText) {
        self.attributedText = [[NSMutableAttributedString alloc] initWithString:self.text];
    }
    NSMutableAttributedString *attrText = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedText];
    if (!([attrText length] > 0 && [[attrText string] rangeOfString:subString].location != NSNotFound && [[attrText string] rangeOfString:subString].length > 0)) return;
    NSRange range = [[attrText string] rangeOfString:subString];
    if (font) {
        [attrText addAttribute:NSFontAttributeName value:font range:range];
    }
    if (color) {
        [attrText addAttribute:NSForegroundColorAttributeName value:color range:range];
    }
    self.attributedText = attrText;
}
/**
 改变部分文字字体和颜色

 @param subString 需要改变的文字
 @param font 改变后的字体
 @param color 改变后的颜色
 */
-(void)setAttributeTextWithText:(NSString *)text subText:(NSString *)subString color:(UIColor *)color font:(UIFont *)font{
    
    NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:text];
    
    if (!([attributedText length] > 0 && [[attributedText string] rangeOfString:subString].location != NSNotFound && [[attributedText string] rangeOfString:subString].length > 0)) return;
    NSRange range = [[attributedText string] rangeOfString:subString];
    
    if (font) {
        [attributedText addAttribute:NSFontAttributeName value:font range:range];
    }
    if (color) {
        [attributedText addAttribute:NSForegroundColorAttributeName value:color range:range];
    }
    self.attributedText = attributedText;
    
}

/**
 将Label.text中所有指定子串改变颜色
 
 @param subString 需要改变的文字
 @param color 改变后的颜色
 */
- (void)resetAllSubString:(NSString *)subString color:(UIColor *)color {
    [self resetAllSubString:subString font:nil color:color];
}


/**
 将Label.text中所有指定子串改变颜色和字体

 @param subString 需要改变的文字
 @param font 改变后的字体
 @param color 改变后的颜色
 */
- (void)resetAllSubString:(NSString *)subString font:(UIFont *)font color:(UIColor *)color {
    if (StringIsEmpty(subString)) return;
    NSArray *strArr = [self.text componentsSeparatedByString:subString];
    if ([strArr count] > 1) {
        NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] init];
        NSMutableDictionary *attrDic = [NSMutableDictionary dictionary];
        if (font) {
            [attrDic setValue:font forKey:NSFontAttributeName];
        }
        if (color) {
            [attrDic setValue:color forKey:NSForegroundColorAttributeName];
        }
        for (NSInteger i = 0; i < strArr.count; i++) {
            [attrStr appendAttributedString:[[NSAttributedString alloc] initWithString:[strArr objectAtIndex:i] attributes:@{NSFontAttributeName : self.font, NSForegroundColorAttributeName : self.textColor}]];
            if (i < strArr.count - 1) {
                [attrStr appendAttributedString:[[NSAttributedString alloc] initWithString:subString attributes:attrDic]];
            }
        }
        self.attributedText = attrStr;
    }
}

#pragma mark - 设置行高
- (void)lineSpacing:(CGFloat)spacing {
    if (!self.text)  return;
    if (!self.attributedText) {
        self.attributedText = [[NSMutableAttributedString alloc] initWithString:self.text];
    }
    NSMutableAttributedString *attrText = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedText];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineBreakMode:NSLineBreakByTruncatingTail];
    [paragraphStyle setLineSpacing:spacing];
    [attrText addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [self.text length])];
    self.attributedText = attrText;
}

- (void)lineSpacing:(CGFloat)spacing alignment:(NSTextAlignment)alignment {
    if (!self.text)  return;
    if (!self.attributedText) {
        self.attributedText = [[NSMutableAttributedString alloc] initWithString:self.text];
    }
    NSMutableAttributedString *attrText = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedText];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setAlignment:alignment];
    [paragraphStyle setLineBreakMode:NSLineBreakByTruncatingTail];
    [paragraphStyle setLineSpacing:spacing];
    [attrText addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [self.text length])];
    self.attributedText = attrText;
}
 
#pragma mark - 设置段间距
- (void)paragraphSpacing:(CGFloat)spacing {
    [self paragraphSpacing:spacing alignment:self.textAlignment];
}

- (void)paragraphSpacing:(CGFloat)spacing alignment:(NSTextAlignment)alignment {
    if (!self.text)  return;
    if (!self.attributedText) {
        self.attributedText = [[NSMutableAttributedString alloc] initWithString:self.text];
    }
    NSMutableAttributedString *attrText = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedText];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setAlignment:alignment];
    [paragraphStyle setParagraphSpacing:spacing];
    [attrText addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [self.text length])];
    self.attributedText = attrText;
}

#pragma mark - 设置行间距、段间距
- (void)lineSpacing:(CGFloat)lineSpacing paragraphSpacing:(CGFloat)paragraphSpacing {
    [self lineSpacing:lineSpacing paragraphSpacing:paragraphSpacing alignment:self.textAlignment];
}

- (void)lineSpacing:(CGFloat)lineSpacing paragraphSpacing:(CGFloat)paragraphSpacing alignment:(NSTextAlignment)alignment {
    if (!self.text)  return;
    if (!self.attributedText) {
        self.attributedText = [[NSMutableAttributedString alloc] initWithString:self.text];
    }
    NSMutableAttributedString *attrText = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedText];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setAlignment:alignment];
    [paragraphStyle setLineBreakMode:NSLineBreakByTruncatingTail];
    [paragraphStyle setLineSpacing:lineSpacing];
    [paragraphStyle setParagraphSpacing:paragraphSpacing];
    [attrText addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [self.text length])];
    self.attributedText = attrText;
}

#pragma mark - 图文混排
- (void)attachmentImage:(UIImage *)image size:(CGSize)size {
    if (!self.attributedText) {
        self.attributedText = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@ ",self.text]];
    }
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedText];
    
    NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
    attachment.image = image;
    //这里bounds的x值并不会产生影响
    attachment.bounds = CGRectMake(0, -2, size.width, size.height);
    [attributedString appendAttributedString:[NSAttributedString attributedStringWithAttachment:attachment]];
    
    self.attributedText = attributedString;
}

#pragma mark - 在字符串中插入图片
- (void)insertAttachmentImage:(UIImage *)image size:(CGSize)size index:(NSInteger)index {
    [self insertAttachmentImage:image size:size offsetY:-2 index:index];
}

- (void)insertAttachmentImage:(UIImage *)image size:(CGSize)size offsetY:(CGFloat)offsetY index:(NSInteger)index {
    NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
    attachment.image = image;
    attachment.bounds = CGRectMake(0, offsetY, size.width, size.height);
    NSMutableAttributedString *resultAttrStr = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedText];
    [resultAttrStr insertAttributedString:[NSAttributedString attributedStringWithAttachment:attachment] atIndex:index];
    self.attributedText = [[NSMutableAttributedString alloc] initWithAttributedString:resultAttrStr];
}

#pragma mark - 多张图片图文混排
- (void)attachmentImages:(NSArray *)images {
    [self attachmentImages:images spacingCount:1];
}

- (void)attachmentImages:(NSArray *)images spacingCount:(NSInteger)spacingCount {
    if (!self.attributedText) {
        if (StringIsNotEmpty(self.text)) {
            self.attributedText = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@ ",self.text]];
        } else {
            self.attributedText = [[NSMutableAttributedString alloc] init];
        }
    }
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedText];
    
    for (NSInteger i = 0; i < images.count; i++) {
        if (spacingCount > 0) {
            for (NSInteger j = 0; j < spacingCount; j++) {
                [attributedString appendAttributedString:[[NSMutableAttributedString alloc] initWithString:@" "]];
            }
        }
        NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
        UIImage *attachImage = [images objectAtIndex:i];
        attachment.image = attachImage;
        //这里bounds的x值并不会产生影响
        attachment.bounds = CGRectMake(0, -2, ceil(attachImage.size.width), ceil(attachImage.size.height));
        [attributedString appendAttributedString:[NSAttributedString attributedStringWithAttachment:attachment]];
    }
    
    self.attributedText = attributedString;
}

#pragma mark - 自适应宽度
- (CGFloat)flexibleWidth
{
    return [self flexibleWidthWithLineSpacing:0.0];
}

- (CGFloat)flexibleWidthWithLineSpacing:(CGFloat)lineSpacing
{
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
    paragraphStyle.lineSpacing = lineSpacing;
    
    CGRect textRect = [self.text boundingRectWithSize:CGSizeMake(MAXFLOAT, CGRectGetHeight(self.frame))
                                              options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
                                           attributes:@{
                                                        NSParagraphStyleAttributeName: paragraphStyle.copy,
                                                        NSFontAttributeName: self.font
                                                        }
                                              context:nil];
    
    if (textRect.size.width + 5 > ScreenWidth - 30 * 2) return ScreenWidth - 30 * 2;
    return textRect.size.width + 5;
}

+ (CGFloat)flexibleWidthWithText:(NSString *)text font:(UIFont *)font height:(CGFloat)height lineSpacing:(CGFloat)lineSpacing
{
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
    paragraphStyle.lineSpacing = lineSpacing;
    
    CGRect textRect = [text boundingRectWithSize:CGSizeMake(MAXFLOAT, height)
                                         options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
                                      attributes:@{
                                                   NSParagraphStyleAttributeName: paragraphStyle.copy,
                                                   NSFontAttributeName: font
                                                   }
                                         context:nil];
    if (text.length > 0 && [[text substringFromIndex:text.length - 1] isEqualToString:@" "]) {
        return textRect.size.width + 12;
    }
    return textRect.size.width + 8;
}

#pragma mark - 自适应高度
+ (CGFloat)flexibleHeightWithText:(NSString *)text font:(UIFont *)font width:(CGFloat)width lineSpacing:(CGFloat)lineSpacing {
    if (StringIsEmpty(text)) {
        return 0;
    }
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = lineSpacing;
    
    CGRect textRect = [text boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX)
                                         options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
                                      attributes:@{
                                                   NSParagraphStyleAttributeName: paragraphStyle.copy,
                                                   NSFontAttributeName: font
                                                   }
                                         context:nil];
    return textRect.size.height;
}

#pragma mark - 可以计算行数、每行文字
- (NSArray *)linesArray {
    NSString *text = [self text];
    
    if (text.length <= 0) {
        return @[];
    }
    
    UIFont *font = [self font];
    CGRect rect = [self frame];
    
    CTFontRef myFont = CTFontCreateWithName(( CFStringRef)([font fontName]), [font pointSize], NULL);
    NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:text];
    [attStr addAttribute:(NSString *)kCTFontAttributeName value:(__bridge  id)myFont range:NSMakeRange(0, attStr.length)];
    CFRelease(myFont);
    CTFramesetterRef frameSetter = CTFramesetterCreateWithAttributedString(( CFAttributedStringRef)attStr);
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathAddRect(path, NULL, CGRectMake(0,0,rect.size.width,100000));
    CTFrameRef frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, 0), path, NULL);
    NSArray *lines = ( NSArray *)CTFrameGetLines(frame);
    NSMutableArray *linesArray = [[NSMutableArray alloc]init];
    for (id line in lines) {
        CTLineRef lineRef = (__bridge  CTLineRef )line;
        CFRange lineRange = CTLineGetStringRange(lineRef);
        NSRange range = NSMakeRange(lineRange.location, lineRange.length);
        NSString *lineString = [text substringWithRange:range];
        CFAttributedStringSetAttribute((CFMutableAttributedStringRef)attStr, lineRange, kCTKernAttributeName, (CFTypeRef)([NSNumber numberWithFloat:0.0]));
        CFAttributedStringSetAttribute((CFMutableAttributedStringRef)attStr, lineRange, kCTKernAttributeName, (CFTypeRef)([NSNumber numberWithInt:0.0]));
        //NSLog(@"''''''''''''''''''%@",lineString);
        [linesArray addObject:lineString];
    }
    
    CGPathRelease(path);
    CFRelease( frame );
    CFRelease(frameSetter);
    return (NSArray *)linesArray;
}

@end
